package cn.tedu.order.service.impl;

import cn.tedu.order.entity.Order;
import cn.tedu.order.feign.AccountClient;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.feign.StorageClient;
import cn.tedu.order.mapper.OrderMapper;
import cn.tedu.order.service.OrderService;
import cn.tedu.order.tcc.OrderTccAction;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.Set;

@Component
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private EasyIdClient easyIdClient;
    @Autowired
    private AccountClient accountClient;
    @Autowired
    private StorageClient storageClient;
    @Autowired
    private OrderTccAction tcc;
    @Override
    @GlobalTransactional     //启动tcc全局事务
    public void create(Order order) {
        //从全局唯一id发号器获得id
        String id = easyIdClient.getNextId("order_business");
        Long orderId = Long.valueOf(id);
        //Long orderId = Math.abs(new Random().nextLong());
        order.setId(orderId);
        //orderMapper.create(order);

        //冻结订单,这里的tcc是动态代理对象，不是原始对象，底层用AOP切入了代码，会拦截调用
        //然后，新建上下文对象并传入目标对象，所以这里可以给一个null值，这里不起作用
        tcc.prepare(null,
                    order.getId(),
                    order.getUserId(),
                    order.getProductId(),
                    order.getCount(),
                    order.getMoney());

        //远程调用storage，减少库存
        storageClient.decrease(order.getProductId(), order.getCount());
        //远程调用account，扣减账户
        accountClient.decrease(order.getUserId(), order.getMoney());
    }
}
